import Vue from "vue";
import VueRouter from "vue-router";

// 进度条
import NProgress from "nprogress";
import "nprogress/nprogress.css";

import store from "@/store/index";
import util from "@/libs/util.js";
// 路由数据
import routes from "./routes";

// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return VueRouterPush.call(this, location).catch((err) => err);
};
const VueRouterReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
  return VueRouterReplace.call(this, location).catch((err) => err);
};

Vue.use(VueRouter);

const createRouter = () =>
  new VueRouter({
    routes,
    // mode: 'history',
    base: "",
  });

const router = createRouter();

/**
 * 路由拦截
 * 权限验证
 */
let flag = 0;
router.beforeEach(async (to, from, next) => {
  // 进度条
  NProgress.start();
  if (to.meta.white) {
    next();
    flag = 0;
  } else {
    // 验证用户是否登录
    const token = util.cookies.get("token");
    if (token) {
      if (!flag) {
        // 刷新页面执行
        await store.dispatch("d2admin/router/load", router);
        await store.dispatch("d2admin/page/isLoaded");
        setTimeout(() => {
          next(to, true);
        }, 0);
      } else {
        // 取消上一个路由的pending请求
        store.commit("custom/axios/clearCancel");
        next();
      }
      flag = 1;
    } else {
      // 兼容white逻辑
      next({ name: from.meta.white ? from.name : "login", query: from.query });
      NProgress.done();
      flag = 0;
    }
  }
});

router.afterEach((to) => {
  // 进度条
  NProgress.done();
  // 多页控制 打开新的页面
  store.dispatch("d2admin/page/open", to);
  // 更改标题
  util.title(to.meta.title);
});

// 重置路由
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
}

export default router;
